﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Protocol.WebApi
{
    public class WebApiUtil
    {
        private HttpClient client;
        public static Encoding _Encoding { get; set; } = Encoding.UTF8;

        public WebApiUtil(string uri, int timeout)
        {
            client = new HttpClient
            {
                BaseAddress = new Uri(uri),
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                Timeout = TimeSpan.FromMilliseconds(timeout)
            };

        }

        ~WebApiUtil()
        {
            client.Dispose();
        }

        /// <summary>
        ///  异步发送请求
        /// </summary>
        /// <param name="post_data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostRequestAsync(string post_data, string uri = "")
        {
            string address = uri;
            if (uri == "")
                address = client.BaseAddress.AbsoluteUri;

            if (uri.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            var content = new StringContent(post_data);
            //Console.WriteLine(str);
            //Console.WriteLine(Encoding.UTF8.GetString(await content.ReadAsByteArrayAsync()));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded")
            {
                CharSet = "utf-8"
            };
            var response = await client.PostAsync(address, content);
            return response;
        }
        /// <summary>
        /// 读取并解析HttpResponseMessage为字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static async Task<string> GetResponseStrAsync(HttpResponseMessage response)
        {
            var result = await response.Content.ReadAsStringAsync();
            response.Dispose();
            return result;
        }

        /// <summary>
        /// 使用同步方法发送请求
        /// </summary>
        /// <param name="post_data"></param>
        /// <param name="uri"></param>
        /// <param name="timeout"></param>
        /// <returns>响应结果</returns>
        public WebResponse PostRequest(string post_data, string uri, int timeout = 1000)
        {
            //string str = "";
            byte[] data = _Encoding.GetBytes(post_data);
            var req = (HttpWebRequest)WebRequest.Create(uri);

            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.Method = "POST";
            req.Timeout = timeout;

            //req.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            //req.Headers.Set(HttpRequestHeader.ContentLength, data.Length);

            using (var s = req.GetRequestStream())
            {
                s.Write(data, 0, data.Length);
            }
            return req.GetResponse();
        }

        /// <summary>
        /// 读取并解析WebResponse为字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static string GetResponseStr(WebResponse response)
        {
            var resp_str = "";
            using (var s = new StreamReader(response.GetResponseStream(),  _Encoding))
            {
                resp_str = s.ReadToEnd();
            }
            return resp_str;
        }
    }
}
